import { Proxy as HadaProxy, CAUtils } from "./lib";
import fs from "fs";
import path from "path";

(async () => {
	// 设置openssl.exe路径
	process.env.OPENSSL_BIN =
		"C:\\Program Files\\OpenSSL-Win64\\bin\\openssl.exe";
	process.env.SETPROXY_EXE_PATH = path.resolve(
		__dirname,
		"../bin/setProxy.exe"
	);

	const port = 8081;

	const rootCA = await CAUtils.generate();

	const proxy = new HadaProxy({
		port,
		// upstreamProxy: "http://127.0.0.1:7890",
		// certAuthority: {
		// 	key: fs.readFileSync(rootCA.keyFilePath, "utf-8"),
		// 	cert: fs.readFileSync(rootCA.crtFilePath, "utf-8"),
		// },
	});

	proxy.on("start", (port) => {
		console.log(
			`证书生成在: ${rootCA.crtFilePath} ,请手动安装到受信任的根证书颁发机构.`
		);
		console.log(`系统代理已帮您设置到：当前端口：${port}`);
		console.log("代理服务启动成功 端口：", port);
	});

	proxy.on("interceptedRequestError", (err, ops) => {
		console.log("interceptedRequestError", err, ops.name);
	});

	proxy.on("flowRateMonitor", (ops) => {
		const {
			uploadSpeed,
			downloadSpeed,
			totalUploadFlow,
			totalDownloadFlow,
		} = ops;
		console.log(
			"上传速度",
			uploadSpeed,
			"KB/s",
			"下载速度",
			downloadSpeed,
			"KB/s",
			"总上传流量",
			totalUploadFlow,
			"KB",
			"总下载流量",
			totalDownloadFlow,
			"KB"
		);
	});

	proxy.on("error", (err) => {
		console.error(err);
	});

	// const requestInterceptor = proxy.intercepted(
	// 	{
	// 		name: "test",
	// 		lifeCycle: "request",
	// 		test: ({ request }) => {
	// 			return !!request.headers["authorization"];
	// 		},
	// 	},
	// 	async (ctx) => {
	// 		const { request, response } = ctx;

	// 		const body = request.body?.toString("utf8");
	// 		console.log("请求数据", body);
	// 		ctx.setData("user_id", "1234567890");
	// 		request.body = Buffer.from("activityId=1828615802120458");
	// 		// response.body = Buffer.from("{}");
	// 		requestInterceptor.pause();
	// 		setTimeout(() => {
	// 			console.log("恢复拦截器");
	// 			requestInterceptor.resume();
	// 		}, 5000);
	// 	}
	// );
})();
